package cn.lumora.core.security.rea;

import cn.lumora.core.util.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * RSA密钥存储服务，负责管理和访问Redis中的RSA密钥
 */
@Service
@Slf4j
public class RSAKeyStorageService {

    // Redis键常量
    private static final String RSA_PUBLIC_KEY = "rsa:public_key";
    private static final String RSA_PRIVATE_KEY = "rsa:private_key";
    private static final String RSA_PUBLIC_KEY_VERSION = "rsa:public_key_version";
    
    private final RedisService redisService;

    public RSAKeyStorageService(RedisService redisService) {
        this.redisService = redisService;
    }
    
    /**
     * 存储RSA密钥对到Redis
     * 
     * @param publicKey 公钥字符串
     * @param privateKey 私钥字符串
     */
    public void storeKeyPair(String publicKey, String privateKey) {
        try {
            // 存储公钥并设置24小时过期
            redisService.setEx(RSA_PUBLIC_KEY, publicKey, 24 * 60 * 60);

            // 存储私钥并设置24小时过期
            redisService.setEx(RSA_PRIVATE_KEY, privateKey, 24 * 60 * 60);

            // 增加公钥版本号，用于跟踪密钥轮换
            redisService.increment(RSA_PUBLIC_KEY_VERSION, 1);
        }catch (Exception e){
            log.error("RSAKeyStorageService.storeKeyPair error: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 获取当前公钥
     * 
     * @return 当前公钥字符串，如果不存在返回null
     */
    public String getPublicKey() {
        return redisService.get(RSA_PUBLIC_KEY);
    }
    
    /**
     * 获取当前私钥
     * 
     * @return 当前私钥字符串，如果不存在返回null
     */
    public String getPrivateKey() {
        return redisService.get(RSA_PRIVATE_KEY);
    }
    
    /**
     * 获取当前公钥版本
     * 
     * @return 当前公钥版本号
     */
    public Long getCurrentPublicKeyVersion() {
        String versionStr = redisService.get(RSA_PUBLIC_KEY_VERSION);
        return versionStr != null ? Long.valueOf(versionStr) : 0L;
    }
}
